import { defineStore } from 'pinia'
import { ref } from 'vue'
import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { isHttp, isEmpty } from "@/utils/validate"
import { getInfo, login, logout } from '@/api/login'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { genUUID } from '@/utils/common'
import defAva from '@/static/images/profile.jpg'

const baseUrl = config.baseUrl

// 辅助函数：时间戳 yyyymmddhhmmss
function formatTsYYYYMMDDHHMMSS() {
  const d = new Date()
  const pad = (n) => (n < 10 ? '0' + n : '' + n)
  const yyyy = d.getFullYear()
  const mm = pad(d.getMonth() + 1)
  const dd = pad(d.getDate())
  const hh = pad(d.getHours())
  const mi = pad(d.getMinutes())
  const ss = pad(d.getSeconds())
  return `${yyyy}${mm}${dd}${hh}${mi}${ss}`
}

function buildRequestId(userId) {
  const idStr = userId ?? ''
  return `R-${idStr}${formatTsYYYYMMDDHHMMSS()}`
}

function buildChannelName(userId) {
  const idStr = userId ?? ''
  // 生成3位UUID，确保每次不重复
  const shortUuid = genUUID().replace(/-/g, '').substring(0, 3)
  return `agora_${idStr}_${shortUuid}`
}

function buildSixDigitUid() {
  const uuid = genUUID() || ''
  const digits = uuid.replace(/\D/g, '')
  const six = (digits + '000000').slice(0, 6)
  return parseInt(six, 10)
}

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken())
  const id = ref(storage.get(constant.id))
  const name = ref(storage.get(constant.name))
  const avatar = ref(storage.get(constant.avatar))
  const roles = ref(storage.get(constant.roles))
  const permissions = ref(storage.get(constant.permissions))
  
  // TEN通信相关ID - 初始从存储读，否则留空，待登录/拉取信息后基于id生成
  const requestId = ref(storage.get(constant.requestId) || '')
  const channelName = ref(storage.get(constant.channelName) || '')
  const uid = ref(storage.get(constant.uid) || '')
  
  // 用户画像缓存
  const userProfile = ref(null)
  const userProfileLoading = ref(false)

  const SET_TOKEN = (val) => {
    token.value = val
  }
  const SET_ID = (val) => {
    id.value = val
    storage.set(constant.id, val)
  }
  const SET_NAME = (val) => {
    name.value = val
    storage.set(constant.name, val)
  }
  const SET_AVATAR = (val) => {
    avatar.value = val
    storage.set(constant.avatar, val)
  }
  const SET_ROLES = (val) => {
    roles.value = val
    storage.set(constant.roles, val)
  }
  const SET_PERMISSIONS = (val) => {
    permissions.value = val
    storage.set(constant.permissions, val)
  }
  
  // 设置TEN通信相关ID
  const SET_REQUEST_ID = (val) => {
    requestId.value = val
    storage.set(constant.requestId, val)
  }
  const SET_CHANNEL_NAME = (val) => {
    channelName.value = val
    storage.set(constant.channelName, val)
  }
  const SET_UID = (val) => {
    uid.value = val
    storage.set(constant.uid, val)
  }

  // 生成TEN通信相关ID的独立方法
  const generateTenIds = (userId) => {
    if (!userId) {
      console.warn('generateTenIds: userId is required')
      return
    }
    
    const newRequestId = buildRequestId(userId)
    const newChannelName = buildChannelName(userId)
    const newUid = buildSixDigitUid()
    
    SET_REQUEST_ID(newRequestId)
    SET_CHANNEL_NAME(newChannelName)
    SET_UID(newUid)
    
    console.log('Generated TEN IDs:', {
      requestId: newRequestId,
      channelName: newChannelName,
      uid: newUid
    })
  }

  // 登录
  const loginAction = (userInfo) => {
    const username = userInfo.username.trim()
    const password = userInfo.password
    const code = userInfo.code
    const uuid = userInfo.uuid
    return new Promise((resolve, reject) => {
      login(username, password, code, uuid).then(res => {
        setToken(res.token)
        SET_TOKEN(res.token)
        
        // 设置用户ID
        SET_ID(username)

        // 生成TEN通信相关ID
        generateTenIds(username)
        
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }

  // 获取用户信息
  const getInfoAction = () => {
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        const user = res.user
        let ava = user.avatar || ""
        if (!isHttp(ava)) {
          ava = (isEmpty(ava)) ? defAva : baseUrl + ava
        }
        const userid = (isEmpty(user) || isEmpty(user.userId)) ? "" : user.userId
        const username = (isEmpty(user) || isEmpty(user.userName)) ? "" : user.userName
        if (res.roles && res.roles.length > 0) {
          SET_ROLES(res.roles)
          SET_PERMISSIONS(res.permissions)
        } else {
          SET_ROLES(['ROLE_DEFAULT'])
        }
        SET_ID(userid)
        SET_NAME(username)
        SET_AVATAR(ava)
        
        // 如果TEN通信相关ID不存在，则基于ID生成
        if (!requestId.value || !channelName.value || !uid.value) {
          generateTenIds(userid)
        }
        
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }

  // 退出系统
  const logOutAction = () => {
    return new Promise((resolve, reject) => {
      logout(token.value).then(() => {
        SET_TOKEN('')
        // 清空内存中的用户ID，避免 WebSocket 依据旧ID继续重连
        SET_ID('')
        SET_ROLES([])
        SET_PERMISSIONS([])
        SET_REQUEST_ID('')
        SET_CHANNEL_NAME('')
        SET_UID('')
        removeToken()
        storage.clean()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }

  // 获取用户画像（带缓存）
  const getUserProfileCached = async (userId) => {
    if (!userId) return null
    
    // 如果正在加载，等待完成
    if (userProfileLoading.value) {
      return new Promise((resolve) => {
        const checkLoading = () => {
          if (!userProfileLoading.value) {
            resolve(userProfile.value)
          } else {
            setTimeout(checkLoading, 100)
          }
        }
        checkLoading()
      })
    }
    
    // 如果已有缓存，直接返回
    if (userProfile.value) {
      return userProfile.value
    }
    
    // 开始加载
    userProfileLoading.value = true
    try {
      const { getUserProfile } = await import('@/api/pc/elderly')
      const response = await getUserProfile(userId)
      if (response && response.code === 200 && response.data) {
        userProfile.value = response
        return response
      }
      return null
    } catch (error) {
      console.warn('Failed to fetch user profile:', error)
      return null
    } finally {
      userProfileLoading.value = false
    }
  }

  // 清除用户画像缓存
  const clearUserProfileCache = () => {
    userProfile.value = null
    userProfileLoading.value = false
  }

  // 强制刷新用户画像（清除缓存后重新获取）
  const refreshUserProfile = async (userId) => {
    clearUserProfileCache()
    if (userId) {
      return await getUserProfileCached(userId)
    }
    return null
  }

  return {
    token,
    id,
    name,
    avatar,
    roles,
    permissions,
    requestId,
    channelName,
    uid,
    userProfile,
    userProfileLoading,
    SET_ID,
    SET_NAME,
    SET_AVATAR,
    SET_REQUEST_ID,
    SET_CHANNEL_NAME,
    SET_UID,
    generateTenIds,
    getUserProfileCached,
    clearUserProfileCache,
    refreshUserProfile,
    login: loginAction,
    getInfo: getInfoAction,
    logOut: logOutAction
  }
})
